#!/usr/bin/python2.4
#
# Copyright 2011 Google Inc. All Rights Reserved.

"""This module will accept the checkout checkout parameters as 'get' values
and pass on the same to the checkout API as a post request.
"""

__author__ = 'nikhildev@google.com (Nikhil Dev)'

import base64
import os
from django.utils import simplejson as json
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from pprint import pformat
from re import match
from simplejson import loads
from urllib import urlencode, quote
from urllib2 import urlopen, Request, HTTPError

base_template = os.path.join(os.path.dirname(__file__), 'templates/base.html')


class MainPage(webapp.RequestHandler):
  def get(self):
    self.response.out.write(template.render(base_template, ''))
  def post(self):
    merchant_id = self.request.get('merchant_id')
    item_name = self.request.get('item_name')
    item_description = self.request.get('item_description')
    item_quantity = self.request.get('quantity')
    item_price = self.request.get('price')
    item_currency = self.request.get('currency')
    button_size = self.request.get('button_size')
    pass_on = {'merchant_id': merchant_id,
               'item_name': item_name,
               'item_description': item_description,
               'item_quantity': item_quantity,
               'item_price': item_price,
               'item_currency': item_currency,
               'button_size': button_size,
              }

    cart_url = 'localhost:8081/posteet/?merchantid=%s&item-name=%s&item-description=%s&item-quantity=%s&item-price=%s&item-currency=%s' % (
                   merchant_id,
                   item_name,
                   item_description,
                   item_quantity,
                   item_price,
                   item_currency)

    image_url = 'https://checkout.google.com/buttons/checkout.gif?merchant_id=%s&%s&style=trans&variant=text&loc=en_US' % (
                    merchant_id,
                    button_size)

    short_url = ShortenUrl(cart_url)
    button_code = '<a href="http://%s"><img src="%s"></a>' % (cart_url,
                                                       image_url
                                                      );
    self.response.out.write(template.render(base_template,
                                            {'cart_url': 'http://' + cart_url,
                                             'image_url': image_url,
                                             'short_url': short_url,
                                             'button_code': button_code,
                                             'pass_on': pass_on,
                                            }
                                           )
                           )


class Posteet(webapp.RequestHandler):
  def get(self):
    """The URLs below are for sandbox testing."""
    #checkout_url = 'https://sandbox.google.com/checkout/cws/v2/Merchant/%s/checkoutForm'
    #shopping_cart_url = 'https://sandbox.google.com/checkout/view/buy?o=shoppingcart&shoppingcart=%s'
    checkout_url = 'https://checkout.google.com/api/checkout/v2/checkoutForm/Merchant/%s'
    shopping_cart_url = 'https://checkout.google.com/buy?o=shoppingcart&shoppingcart=%s'
    error_notification = False

    # Fetching the GET parameters to define the commodity
    merchant_id = self.request.get('merchantid')
    item_name = self.request.get('item-name')
    item_description = self.request.get('item-description')
    item_quantity = self.request.get('item-quantity')
    item_price = self.request.get('item-price')
    item_currency = self.request.get('item-currency')

    headers = {'Content-Type': 'charset=UTF-8',
               'Accept': 'charset=UTF-8',
              }

    # Defining post parameters
    post_params = {'item_name_1': item_name,
                   'item_description_1': item_description,
                   'item_price_1': item_price,
                   'item_quantity_1': item_quantity,
                   'item_currency_1': item_currency,
                   }

    request_url = checkout_url % merchant_id

    try:
      req = Request(request_url, urlencode(post_params), headers)
      html = urlopen(req).read()
    except HTTPError, e:
      if e.code == 400:
        html = False

    # Fetching the indexes of keywords to search for
    if html:
      index_of_shoppingcart = html.find('shoppingcart=')
      index_of_rest = html.find('" id')
      beginning_of_id = index_of_shoppingcart + 13

      # The shopping cart id is 15 chars long
      shopping_cart_key =  html[beginning_of_id:beginning_of_id + 15]

      redirect_url = shopping_cart_url % shopping_cart_key
      
      self.redirect(redirect_url)
    else:
      print 'Incorrect Merchant ID or other data. Regenerate code with correct ones'


def ShortenUrl(url):
  google_shortner = 'https://www.googleapis.com/urlshortener/v1/url'
  url_json = json.dumps({'longUrl': url})
  req = Request(google_shortner, data=url_json)
  # req.add_header('User-Agent', 'toolbar')
  req.add_header('Content-Type', 'application/json')
  try:
    results = json.load(urlopen(req))
    return results['id']
  except HTTPError, e:
    return e


application = webapp.WSGIApplication([
    ('/', MainPage),
    ('/posteet/', Posteet),
    ],
    debug=True)


def main():
  run_wsgi_app(application)

if __name__ == '__main__':
  main()
